
import { computed, ref, unref, nextTick } from 'vue';
import type { Ref } from 'vue';
import * as echarts from 'echarts';
import 'echarts-gl' // 3D
import 'echarts-wordcloud' // 词云
export function useECharts(elRef: Ref<HTMLDivElement>, theme: 'light' | 'dark' | 'default' = 'default') {
  let chartInstance: echarts.ECharts | null = null; // 实例
  const cacheOptions = ref({}) as any; // 缓存配置

  const getOptions = computed(() => {
    return {
      backgroundColor: 'transparent', // 设置背景透明
      ...cacheOptions.value
    } as any;
  })

  const initCharts = (t = theme) => {
    const el = unref(elRef);
    if (!el || !unref(el)) {
      return
    }
    chartInstance = echarts.init(el, t);
  }

  const setOptions = (options: any, clear = true) => {
    cacheOptions.value = options;
    return new Promise((resolve) => {
      if (unref(elRef)?.offsetHeight === 0) {
        setTimeout(() => {
          setOptions(unref(getOptions))
          resolve(null)
        }, 30)
      }
      nextTick(() => {
        setTimeout(() => {
          if (!chartInstance) {
            console.log("第一次，没有实例")
            initCharts(theme)
            if (!chartInstance) {
              console.log("内层判断，没有实例")
              return
            }
          }
          clear && chartInstance?.clear()
          chartInstance?.setOption(unref(getOptions));
          resolve(null)
        }, 30)
      })
    })
  }

  const getInstance: () => echarts.ECharts | null = () => {
    if (!chartInstance) {
      initCharts(theme)
    }
    return chartInstance
  }

  const resize = () => {
    chartInstance?.resize();
  }

  return {
    setOptions,
    echarts,
    getInstance,
    resize
  }
}